﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;

using CE.Configuration;
using CE.Global;
using CE.User;
using CE.Image;
using CE.CarInsurance;
using CE.Mail;
using CE.Company;
using CE.Database;
using CE.Promotion;

public partial class promotion_promotion : MyLanguageBasePage
{
    CE.User.Profile _profile = null;
    CE.User.ProfileDB _profiledb = null;
    Contact _contact = null;
    ContactDB _contactdb = null;
    string _redirectUrl = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        string _strPromoActive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.IsPromoActive");
        if (_strPromoActive == "0")
        {
            if (Session[CE.Global.General.Guest] == null)
            {
                Response.Redirect("~/Default.aspx");
            }
        }
        Master.Page.Title = Resources.Title.CITitle;

        LiteralControl newln = new LiteralControl(Environment.NewLine);
        HtmlMeta language = new HtmlMeta();
        language.Name = "language";
        language.Content = Resources.Title.PageLanguage;

        HtmlMeta keywords = new HtmlMeta();
        keywords.Name = "keywords";
        keywords.Content = Resources.Title.CIKeyword;
        HtmlMeta description = new HtmlMeta();
        description.Name = "description";
        description.Content = Resources.Title.CIDescription;

        Page.Header.Controls.AddAt(10, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(11, language);
        Page.Header.Controls.AddAt(12, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(13, keywords);
        Page.Header.Controls.AddAt(14, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(15, description);
        if (!Page.IsPostBack)
        {
            SetCoverageComDate();
        }
    }


    private string EmailAddress
    {
        get { return txtEmailPop.Text.Trim(); }
    }

    #region call back pop
    protected void btnCallforDiscount_Click(object sender, EventArgs e)
    {
        HtmlAnchor aPromotion = (HtmlAnchor)sender;
        lblPromotionName.Text = aPromotion.Name;
        ShowCallPopup();
        mpeCallPop.Show();
    }

    private void ShowCallPopup()
    {
        if (Session[General.UserId] != null)
        {
            Int64 UserId = Convert.ToInt64(Session[General.UserId]);
            _profile = new CE.User.Profile();
            _profiledb = new ProfileDB();
            _contact = new Contact();
            _contactdb = new ContactDB();

            _profile = _profiledb.GetProfile(UserId);
            _profiledb = null;

            if (_profile != null)
            {
                txtCallMeFullNamePop.Text = _profile.FirstName + " " + _profile.SurName;


                _contact = _contactdb.GetContact(UserId);
                if (_contact != null)
                {
                    usrCallMePhoneNo.PhoneNo = _contact.Mobile;
                    txtEmailPop.Text = _contact.Email;
                    txtEmailPop.ReadOnly = true;

                }

                _profile = null;
            }
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (usrCallMePhoneNo.GetPhoneNo().Length == 10)
        {
            int _isexistuser = 1;
            Int64 _userId = 0;
            Account _useraccount = new Account();
            AccountDB _useraccountdb = new AccountDB();

            if (Session[General.UserId] == null)
            {
                _useraccount = _useraccountdb.CheckEmail(EmailAddress, Convert.ToInt32(CE.Global.CEUserType.Customer));
                if (_useraccount != null && _useraccount.CEID > 0)
                {
                    _userId = _useraccount.CEID;
                }
                else
                {
                    if (UpdateProfile(_userId, 0) > 0)
                    {
                        SendMailToUser(EmailAddress, Session[CE.Global.General.UserName].ToString(), usrCallMePhoneNo.PhoneNo); //txtEmailAddress.Text.Trim()

                        Session["CLASSTYPE"] = "1";
                        lblMessage.Text = "Saved successfully!";
                        _userId = Convert.ToInt64(Session[General.UserId].ToString());
                        _isexistuser = 0;
                    }
                }
            }
            else
            {
                _userId = Convert.ToInt64(Session[General.UserId].ToString());
            }

            string _message = "";
            string _title = "";

            txtCallMeFullNamePop.Text = General.ClearScriptTag(txtCallMeFullNamePop.Text);
            _message = "Customer Name: " + Server.HtmlEncode(txtCallMeFullNamePop.Text);
            _title = "Call Me Promotion - Call Me Promotion request by " + Server.HtmlEncode(txtCallMeFullNamePop.Text);
            if (IsValid)
            {
                Int64 _result = 0;
                ContactUser _cu = new ContactUser();
                ContactUserDB _cudb = new ContactUserDB();

                string strInsType = "1";

                _cu.InsuranceType = "CI-" + strInsType;


                //_cu.ProductId = Convert.ToInt64(Session[General.CarId].ToString());
                _cu.RefCEUserId = _userId;

                _cu.ProviderCompanyId = 0;
                _cu.ContactNo = usrCallMePhoneNo.GetPhoneNo();
                _cu.FullName = Server.HtmlEncode(txtCallMeFullNamePop.Text);
                _cu.CallTime = Convert.ToInt16(ddlCallMeTime.Text);

                if (Request.Params["spc"] != null)
                {
                    if (Request.Params["spc"].ToString() == "1")
                    {
                        _cu.Info1 = "GG Promotion";
                    }
                }

                _result = _cudb.Insert(_cu);

                if (_result > 0)
                {
                    _profile = new CE.User.Profile();
                    _profiledb = new ProfileDB();
                    _profile = _profiledb.GetProfile(_cu.RefCEUserId);
                    if (_profile != null && _profile.ProfileId > 0)
                    {
                        _profile.SurName = string.Empty;
                        _profile.FirstName = Server.HtmlEncode(txtCallMeFullNamePop.Text);
                        _profiledb.Insert(_profile);
                    }
                    _profile = null;
                    _profiledb = null;

                    _contact = new Contact();
                    _contactdb = new ContactDB();
                    _contact = _contactdb.GetContact(_cu.RefCEUserId);
                    if (_contact != null && _contact.ContactId > 0)
                    {
                        _contact.Mobile = usrCallMePhoneNo.GetPhoneNo();
                        _contactdb.Insert(_contact);
                    }
                    _contact = null;
                    _contactdb = null;
                    string _promotionName = "";
                    string _promotionImageUrl = "";
                    if (lblPromotionName.Text == "Promotion1")
                    {
                        _promotionName = "1.Eco car เครื่อง 1500cc.ซ่อมห้างเริ่มต้น 12,000 บาท  ทุน 350,000 บาท  *ไม่มีค่าเสียหายส่วนแรก *ปี 2010 - ปี 2014";
                        _promotionImageUrl = Resources.ImageResource.PromotionUrl1;
                    }
                    else if (lblPromotionName.Text == "Promotion2")
                    {
                        _promotionName = "2. กระบะ ซ่อมห้าง เริ่มต้น 14,190 บาท ทุน 400,000-650,000 บาท  *ไม่มีค่าเสียหายส่วนแรก *ปี 2010 - ปี 2014";
                        _promotionImageUrl = Resources.ImageResource.PromotionUrl2;
                    }
                    else if (lblPromotionName.Text == "Promotion3")
                    {
                        _promotionName = "3. งบน้อย ขับน้อย ประกันชั้น 1 ราคา 9,999 บาท *ไม่มีค่าเสียหายส่วนแรก";
                        _promotionImageUrl = Resources.ImageResource.PromotionUrl3;
                    }
                    else if (lblPromotionName.Text == "Promotion4")
                    {
                        _promotionName = "4.SUV รุ่นใหญ่ ซ่อมห้างเริ่มต้น 14,800 บาท ทุน 640,000-1,250,000 บาท *ไม่มีค่าเสียหายส่วนแรก *ปี 2010 - ปี 2014";
                        _promotionImageUrl = Resources.ImageResource.PromotionUrl4;
                    }
                    Promotion _promotion = new Promotion();
                    PromotionDB _promotiondb = new PromotionDB();
                    _promotion.RefCEUserId = _userId;
                    _promotion.PromotionName = _promotionName;
                    _promotion.UserName = txtCallMeFullNamePop.Text;
                    _promotion.Email = txtEmailPop.Text;
                    _promotion.Mobile = usrCallMePhoneNo.GetPhoneNo();
                    _promotion.CommencementMonth = Convert.ToInt32(ddlCoverageComMonth.SelectedValue);
                    _promotion.AgentId = 0;
                    _promotion.IsExistCustomer = _isexistuser;
                    _promotion.CallAt = Convert.ToInt32(ddlCallMeTime.SelectedValue);
                    Int64 _pmresult = _promotiondb.InsertUpdate(_promotion);
                    _promotion = null;
                    _promotiondb = null;
                    if (_pmresult != -1)
                    {
                        ScriptManager.RegisterStartupScript(Page, this.GetType(), "alertThxU", "alert('" + Resources.CarInsurance.CallMeMessage + "')", true);
                        _message += "<img src='http://www.gluaygluay.com" + _promotionImageUrl.Trim() + "' /><br/>";
                        _message += "<br/><br/>Promotion name : " + _promotionName;
                        _message += "<br/><br/>Full Name : " + Server.HtmlEncode(txtCallMeFullNamePop.Text);
                        _message += "<br/><br/>Email : " + txtEmailPop.Text;
                        _message += "<br/><br/>Contact No : " + usrCallMePhoneNo.GetPhoneNo();
                        _message += "<br/><br/>Call Time : " + ddlCallMeTime.SelectedItem.Text;
                        string _emailList = ConfigurationManager.AppSettings["TH.CICallMeMessageReceiver"].ToString();
                        MyMailManager.SendCRMMessage(_emailList, _title, _message);

                        divCallMe.Visible = true;
                        lblCallMeMessage.Text = Resources.CarInsurance.CallMeMessage;

                        txtCallMeFullNamePop.ReadOnly = true;
                        txtEmailPop.ReadOnly = true;
                        ddlCallMeTime.Enabled = false;
                        usrCallMePhoneNo.IsEnabled = false;
                        btnSubmit.Enabled = false;
                        Session[General.UserId] = null;
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(Page, this.GetType(), "alertThxU", "alert('Saving did NOT succees!');", true);
                        lblMessage.Text = "Saving did NOT succeed!";
                    }

                }
            }
        }
    }

    #endregion

    private Int64 UpdateProfile(Int64 UserId, Int64 CarId)
    {
        Int64 _retValue = 0;

        if (UserId != 0)
        {
            _profile = new CE.User.Profile();
            _profiledb = new ProfileDB();

            _contact = new Contact();
            _contactdb = new ContactDB();

            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);

            if (_profile != null)
            {
                #region Update Profile

                _profile.Salutation = ""; // ddlSalutation.GetSalutation();
                txtCallMeFullNamePop.Text = CE.Global.General.ClearScriptTag(txtCallMeFullNamePop.Text.Trim());
                _profile.FirstName = HttpUtility.HtmlEncode(txtCallMeFullNamePop.Text);
                _profile.SurName = ""; //txtSurName.Text;
                if (_profile.DOB.Year == 1900)
                {
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _profile.DOB = dteDOB;
                }
                if (_profile.Gender.ToString().Trim() == "")
                {
                    _profile.Gender = 'M'; //Convert.ToChar(ddlGender.GetGender());
                }
                _profile.Status = "Complete";

                _retValue = _profiledb.Insert(_profile);

                if (_retValue > 0 && _contact != null)
                {
                    _contact.Mobile = usrCallMePhoneNo.GetPhoneNo();
                    _contact.Status = true;

                    _retValue = _contactdb.Insert(_contact);
                }
                else
                {
                }

                if (_retValue > 0)
                {
                    if (_profile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _profile.FirstName + " " + _profile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _profile.SurName;
                    }
                    Session[General.UserPhoneNo] = usrCallMePhoneNo.GetPhoneNo();
                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                        Convert.ToInt32(CE.Global.CEUserType.Provider))
                    {
                        Session[CE.Global.General.ProviderProfileFirstTime] = "0";
                    }
                }
                else
                {
                }

                _profile = null;
                _contact = null;
                #endregion
            }
        }
        else
        {
            _retValue = SaveNewCustomer();
            UserId = _retValue;
        }

        if (_retValue > 0 && CarId > 0)
        {
            CarDetailTH _cardetail = new CarDetailTH();
            CarDetailTHDB _cardetaildb = new CarDetailTHDB();
            _cardetail = _cardetaildb.GetCar(CarId, UserId);


            _profile = new CE.User.Profile();
            _profiledb = new ProfileDB();
            _profile = _profiledb.GetProfile(UserId);

            if (_cardetail != null)
            {
                _cardetail.Info5 = EmailAddress; //txtEmailAddress.Text;
                _cardetail.Info6 = usrCallMePhoneNo.GetPhoneNo();
                _cardetail.Info7 = txtCallMeFullNamePop.Text.Trim();
                txtCallMeFullNamePop.Text = CE.Global.General.ClearScriptTag(txtCallMeFullNamePop.Text.Trim());
                if (txtCallMeFullNamePop.Text.Trim().Length > 0)
                {
                    _cardetail.Info8 = Server.HtmlEncode(txtCallMeFullNamePop.Text.Trim());
                }
                if (_profile.Gender.ToString().Trim() != "")
                {
                    _cardetail.Info9 = _profile.Gender.ToString(); //ddlGender.GetGender();
                }
                else
                {
                    _cardetail.Info9 = "M"; //ddlGender.GetGender();
                }
                if (_profile.DOB.Year == 1900)
                {
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _cardetail.Info10 = dteDOB.ToString("dd-MMM-yyyy"); //usrDOB.GetDate().ToString("dd-MMM-yyyy");
                }
                else
                {
                    _cardetail.Info10 = _profile.DOB.ToString("dd-MMM-yyyy");
                }
                _cardetail.Info11 = _profile.Occupation.ToString(); //Resources.CarInsurance.CorporateEmployee; //ddlOccupation.GetOccupation();
                _cardetail.Info12 = "";// ddlJobNature.GetJobNature();
                _cardetail.Info13 = "";// ddlMaritalStatus.GetMaritalStatus();
                _cardetail.Info14 = "";// ddlYearDriveSg.Text;
                _cardetail.Info15 = "";// ddlSalutation.GetSalutation();
                _cardetail.RefCEUserId = UserId;
            }
            _profile = null;

            //RefUserId only update
            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            _carpolicy = _carpolicydb.GetCarPolicy(CarId, UserId);
            _carpolicy.RefCEUserId = UserId;

            _retValue = _cardetaildb.Insert(_cardetail);

            _retValue = _carpolicydb.Insert(_carpolicy);

            //update RefIds
            CarDetailTHDB cardb = new CarDetailTHDB();
            cardb.UpdateCarDetailPolicy(CarId, UserId);

            if (_retValue <= 0)
            {
            }
        }

        return _retValue;
    }
    private bool SendMailToUser(string EmailAddress, string UserName, string AuthCode)
    {
        bool _retVal = false;
        _retVal = CE.Email.Welcome.SendMail(EmailAddress, UserName, AuthCode);
        return _retVal;
    }
    private Int64 SaveNewCustomer()
    {
        #region New Customer
        Int64 _retVal = 0;
        if (Page.IsValid)
        {

            Account _useraccount = new Account();
            AccountDB _useraccountdb = new AccountDB();

            if (_useraccountdb.IsAlreadyExist(EmailAddress, Convert.ToInt32(CE.Global.CEUserType.Customer))) //txtEmailAddress.Text.Trim()
            {
                txtEmailPop.ControlStyle.CssClass = "validationError";
                _retVal = 0;
            }
            else
            {
                Profile _userprofile = new Profile();
                ProfileDB _userprofiledb = new ProfileDB();
                Contact _contact = new Contact();
                ContactDB _contactdb = new ContactDB();

                long _result = -1;

                _useraccount.Email = EmailAddress.ToLower();
                string _authcode = usrCallMePhoneNo.GetPhoneNo();
                _useraccount.AuthCode = _authcode;
                _useraccount.UserId = "CEUSERAUTOIDCI";
                _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
                _useraccount.IsAcceptTC = false;
                _useraccount.Status = true;
                _useraccount.RefCEUserID = -1;
                _result = _useraccountdb.Insert(_useraccount);
                _useraccount.CEID = _result;
                _retVal = _useraccount.CEID;
                if (_result > 0)
                {
                    Session[General.UserId] = _retVal;
                    _userprofile.Salutation = ""; //ddlSalutation.GetSalutation();
                    _userprofile.FirstName = Server.HtmlEncode(txtCallMeFullNamePop.Text);
                    _userprofile.SurName = "";
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _userprofile.DOB = dteDOB;
                    _userprofile.Gender = 'M'; //Convert.ToChar(ddlGender.GetGender());

                    _userprofile.Occupation = Convert.ToInt32("54");
                    _userprofile.Status = "Complete";
                    _userprofile.RefCEUserId = _useraccount.CEID;
                    _userprofile.IsAcceptTC = true;
                    _result = _userprofiledb.Insert(_userprofile);

                    _contact.Email = _useraccount.Email;
                    _contact.Mobile = usrCallMePhoneNo.GetPhoneNo();

                    _contact.Status = true;
                    _contact.RefCEUserId = _useraccount.CEID;
                    _result = _contactdb.Insert(_contact);

                    if (_result > 0)
                    {
                        Session[CE.Global.General.UserId] = _useraccount.CEID;
                        Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                        Session[CE.Global.General.UserEmail] = _useraccount.Email;
                        Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                        Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                        Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    }

                }

            }
        }
        else
        {
            _retVal = 0;
        }

        return _retVal;
        #endregion
    }

    private void SetCoverageComDate()
    {
        CultureInfo ci = CultureInfo.CurrentCulture;
        DateTime dtNow = new DateTime();
        dtNow = General.GetUTCDateTime().AddDays(2);

        DateTime dtEndMonth = new DateTime();
        dtEndMonth = General.GetUTCDateTime().AddDays(120);

        int mthDiff = ((dtEndMonth.Year - dtNow.Year) * 12) + dtEndMonth.Month - dtNow.Month;
        for (int m = 0; m <= mthDiff; m++)
        {
            DateTime dtTemp = dtNow.AddMonths(m);
            string strDate = dtTemp.ToString("MM", new CultureInfo("en-US"));
            ddlCoverageComMonth.Items.Add(new ListItem(dtTemp.ToString("MMMM yyyy", ci), strDate));
        }

        DateTime dtNow2 = new DateTime();
        dtNow2 = General.GetUTCDateTime().AddDays(14);
        ddlCoverageComMonth.SelectedIndex = ddlCoverageComMonth.Items.IndexOf(ddlCoverageComMonth.Items.FindByValue(dtNow2.Date.Month.ToString("00") + dtNow2.Date.Year.ToString("0000")));

       
    }
}